<template>
  <div class="reviews-page">
    <div class="container">
      <div class="page-header">
        <h1>评价管理</h1>
        <div class="review-tabs">
          <el-tabs v-model="activeTab" @tab-change="handleTabChange">
            <el-tab-pane label="我的评价" name="my-reviews" />
            <el-tab-pane label="待评价" name="pending" />
          </el-tabs>
        </div>
      </div>

      <div class="reviews-content">
        <!-- 我的评价 -->
        <div v-if="activeTab === 'my-reviews'" class="my-reviews-section">
          <div v-if="myReviews.length > 0" class="reviews-list">
            <div v-for="review in myReviews" :key="review.id" class="review-card">
              <div class="review-header">
                <div class="property-info">
                  <div class="property-details">
                    <h3>房源名称: {{ review.propertyName }}</h3>
                    <div class="booking-info">
                      <span>订单编号：{{ review.bookingNo }}</span>
                    </div>
                  </div>
                </div>
                <div class="review-actions">
                  <el-button @click="editReview(review.id)">编辑</el-button>
                  <el-button type="danger" @click="deleteReview(review.id)">删除</el-button>
                </div>
              </div>
              
              <div class="review-content">
                <div class="rating-section">
                  <div class="rating-item">
                    <span>总体评分</span>
                    <el-rate v-model="review.rating" disabled />
                  </div>
                  <div class="rating-breakdown">
                    <div class="rating-detail">
                      <span>清洁度</span>
                      <el-rate v-model="review.cleanlinessRating" disabled />
                    </div>
                    <div class="rating-detail">
                      <span>入住体验</span>
                      <el-rate v-model="review.checkInRating" disabled />
                    </div>
                    <div class="rating-detail">
                      <span>性价比</span>
                      <el-rate v-model="review.valueRating" disabled />
                    </div>
                  </div>
                </div>
                
                <div class="review-text">
                  <p>{{ review.content }}</p>
                </div>
                
                <!-- 商家回复 -->
                <div v-if="review.replyContent" class="host-reply">
                  <div class="reply-header">
                    <el-icon class="reply-icon"><ChatDotRound /></el-icon>
                    <span class="reply-label">房东回复</span>
                    <span class="reply-date" v-if="review.replyAt">· {{ formatDate(review.replyAt) }}</span>
                  </div>
                  <div class="reply-content">
                    {{ review.replyContent }}
                  </div>
                </div>
                
                <div class="review-meta">
                  <span class="review-date">评价时间：{{ formatDate(review.createdAt) }}</span>
                </div>
              </div>
            </div>
          </div>
          
          <div v-else class="empty-state">
            <el-empty description="暂无评价记录">
              <el-button type="primary" @click="$router.push('/orders')">
                去评价
              </el-button>
            </el-empty>
          </div>
        </div>

        <!-- 待评价 -->
        <div v-if="activeTab === 'pending'" class="pending-reviews-section">
          <div v-if="pendingReviews.length > 0" class="pending-list">
            <div v-for="order in pendingReviews" :key="order.id" class="pending-card">
              <div class="order-info">
                <div class="property-image">
                  <img :src="order.property.image" :alt="order.property.title" />
                </div>
                <div class="property-details">
                  <h3>{{ order.property.title }}</h3>
                  <p class="property-location">
                    <el-icon><Location /></el-icon>
                    {{ order.property.location }}
                  </p>
                  <div class="booking-info">
                    <span>入住时间：{{ formatDate(order.checkIn) }} - {{ formatDate(order.checkOut) }}</span>
                  </div>
                </div>
              </div>
              <div class="pending-actions">
                <el-button type="primary" @click="writeReview(order.id)">
                  立即评价
                </el-button>
              </div>
            </div>
          </div>
          
          <div v-else class="empty-state">
            <el-empty description="暂无待评价订单">
              <el-button type="primary" @click="$router.push('/orders')">
                查看订单
              </el-button>
            </el-empty>
          </div>
        </div>


      </div>
    </div>

    <!-- 写评价对话框 -->
    <el-dialog v-model="reviewDialogVisible" :title="reviewForm.id ? '编辑评价' : '写评价'" width="800px">
      <el-form :model="reviewForm" :rules="reviewRules" ref="reviewFormRef" label-width="100px">
        <el-form-item label="总体评分" prop="rating">
          <el-rate v-model="reviewForm.rating" />
        </el-form-item>
        
        <div class="rating-details">
          <el-form-item label="清洁度">
            <el-rate v-model="reviewForm.cleanlinessRating" />
          </el-form-item>
          <el-form-item label="入住体验">
            <el-rate v-model="reviewForm.checkInRating" />
          </el-form-item>
          <el-form-item label="性价比">
            <el-rate v-model="reviewForm.valueRating" />
          </el-form-item>
        </div>
        
        <el-form-item label="评价内容" prop="content">
          <el-input
            v-model="reviewForm.content"
            type="textarea"
            :rows="5"
            placeholder="请分享您的住宿体验..."
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="reviewDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReview">{{ reviewForm.id ? '保存修改' : '提交评价' }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ChatDotRound, Location } from '@element-plus/icons-vue'
import request from '../../api/request'

const route = useRoute()
const router = useRouter()

// 当前标签页
const activeTab = ref('my-reviews')



// 评价对话框
const reviewDialogVisible = ref(false)
const reviewFormRef = ref()

// 评价表单
const reviewForm = reactive({
  id: null, // 编辑时的评论ID
  bookingId: null,
  rating: 0,
  cleanlinessRating: 0,
  checkInRating: 0,
  valueRating: 0,
  content: ''
})

// 表单验证规则
const reviewRules = {
  rating: [
    { required: true, message: '请选择总体评分', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入评价内容', trigger: 'blur' },
    { min: 10, message: '评价内容至少10个字符', trigger: 'blur' }
  ]
}

// 我的评价数据
const myReviews = ref([])

// 待评价数据
const pendingReviews = ref([
  {
    id: 1,
    property: {
      id: 2,
      title: '海边度假别墅',
      location: '青岛·市南区',
      image: 'https://images.unsplash.com/photo-1571896349842-33c89424de2d?w=200&h=150&fit=crop'
    },
    checkIn: '2024-01-18',
    checkOut: '2024-01-20'
  }
])



// 初始化
onMounted(() => {
  // 加载我的评价数据
  loadMyReviews()
  
  // 检查URL参数中是否有待评价的orderId
  const orderId = route.query.orderId
  const tab = route.query.tab
  
  if (tab === 'pending' && orderId) {
    // 切换到待评价标签页
    activeTab.value = 'pending'
    // 自动打开评价对话框
    setTimeout(() => {
      writeReview(orderId)
    }, 100)
  }
})

// 加载我的评价数据
const loadMyReviews = async () => {
  try {
    const response = await request.get('/api/reviews/showAllReviewsByUserId')
    console.log('获取评价数据:', response)
    console.log('response 类型:', typeof response)
    console.log('response 是否为数组:', Array.isArray(response))
    console.log('response.data:', response.data)
    console.log('response.data 是否为数组:', Array.isArray(response.data))
    
    // 后端直接返回List，判断到底是 response 还是 response.data
    if (Array.isArray(response)) {
      myReviews.value = response
    } else if (Array.isArray(response.data)) {
      myReviews.value = response.data
    } else {
      console.error('返回数据格式不正确:', response)
      myReviews.value = []
    }
    
    console.log('最终设置的 myReviews:', myReviews.value)
  } catch (error) {
    console.error('加载评价失败:', error)
    ElMessage.error('加载评价失败')
  }
}

// 标签页切换
const handleTabChange = (tab) => {
  activeTab.value = tab
}

// 编辑评价
const editReview = (reviewId) => {
  const review = myReviews.value.find(r => r.id === reviewId)
  if (review) {
    // 保存当前编辑的评论ID
    reviewForm.id = review.id
    reviewForm.bookingId = review.bookingId
    reviewForm.rating = review.rating
    reviewForm.cleanlinessRating = review.cleanlinessRating
    reviewForm.checkInRating = review.checkInRating
    reviewForm.valueRating = review.valueRating
    reviewForm.content = review.content
    reviewDialogVisible.value = true
  }
}

// 删除评价
const deleteReview = async (reviewId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个评价吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 调用后端删除接口
    const response = await request.delete(`/api/reviews/deleteReviews?id=${reviewId}`)
    console.log('删除评价响应:', response)
    
    ElMessage.success('评价已删除')
    
    // 重新加载评价数据
    loadMyReviews()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除评价失败:', error)
      ElMessage.error('删除评价失败，请重试')
    }
  }
}

// 写评价
const writeReview = (orderId) => {
  // 重置表单（新增时清空id）
  Object.assign(reviewForm, {
    id: null, // 新增时id为null
    bookingId: orderId,
    rating: 0,
    cleanlinessRating: 0,
    checkInRating: 0,
    valueRating: 0,
    content: ''
  })
  reviewDialogVisible.value = true
}

// 提交评价
const submitReview = async () => {
  const valid = await reviewFormRef.value.validate()
  if (!valid) return
  
  try {
    // 判断是新增还是修改
    if (reviewForm.id) {
      // 修改评价
      const updateData = {
        id: reviewForm.id,
        rating: reviewForm.rating,
        content: reviewForm.content,
        cleanlinessRating: reviewForm.cleanlinessRating,
        valueRating: reviewForm.valueRating,
        checkInRating: reviewForm.checkInRating,
        updatedAt: new Date().toISOString()
      }
      
      const response = await request.put('/api/reviews/updateReviews', updateData)
      console.log('修改评价成功:', response)
      ElMessage.success('评价修改成功')
    } else {
      // 新增评价
      const response = await request.post('/api/reviews/addReviews', reviewForm)
      console.log('提交评价成功:', response)
      ElMessage.success('评价提交成功')
    }
    
    reviewDialogVisible.value = false
    
    // 重新加载评价数据
    loadMyReviews()
  } catch (error) {
    console.error('提交评价失败:', error)
    ElMessage.error('评价提交失败，请重试')
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString('zh-CN')
}
</script>

<style scoped>
.reviews-page {
  min-height: 100vh;
  background: #f8f9fa;
  padding: 20px 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  background: white;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 2rem;
  color: #333;
  margin-bottom: 20px;
}

.reviews-content {
  space-y: 20px;
}

.reviews-list {
  space-y: 20px;
}

.review-card {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.property-info {
  display: flex;
  gap: 20px;
}

.property-image {
  width: 120px;
  height: 90px;
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
}

.property-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.property-details h3 {
  font-size: 1.2rem;
  color: #333;
  margin-bottom: 8px;
}

.property-location {
  color: #666;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 0.9rem;
}

.booking-info {
  color: #999;
  font-size: 0.9rem;
}

.reviewer-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.reviewer-details h4 {
  margin: 0 0 5px 0;
  color: #333;
}

.reviewer-details p {
  margin: 0;
  color: #666;
  font-size: 0.9rem;
}

.rating-section {
  margin-bottom: 20px;
}

.rating-item {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 15px;
}

.rating-breakdown {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 15px;
}

.rating-detail {
  display: flex;
  align-items: center;
  gap: 10px;
}

.rating-detail span {
  min-width: 60px;
  color: #666;
  font-size: 0.9rem;
}

.review-text {
  margin-bottom: 20px;
}

.review-text p {
  line-height: 1.6;
  color: #333;
  font-size: 1.1rem;
}

.review-images {
  margin-bottom: 20px;
}

.image-gallery {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.image-gallery img {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.3s;
}

.image-gallery img:hover {
  transform: scale(1.05);
}

.review-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #666;
  font-size: 0.9rem;
}

.review-stats {
  display: flex;
  gap: 20px;
}

.property-reference {
  margin-bottom: 15px;
  color: #666;
}

.property-reference span {
  margin-right: 10px;
}

.pending-list {
  space-y: 20px;
}

.pending-card {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-info {
  display: flex;
  gap: 20px;
}

.reviews-filters {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.rating-details {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

/* 商家回复样式 */
.host-reply {
  margin-top: 20px;
  margin-bottom: 15px;
  padding: 15px 20px;
  background: #f8f9fa;
  border-left: 3px solid #409eff;
  border-radius: 8px;
}

.reply-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
  color: #666;
  font-size: 0.9rem;
}

.reply-icon {
  color: #409eff;
  font-size: 16px;
}

.reply-label {
  font-weight: 600;
  color: #409eff;
}

.reply-date {
  color: #999;
  font-size: 0.85rem;
}

.reply-content {
  color: #333;
  line-height: 1.6;
  font-size: 0.95rem;
}

.empty-state {
  background: white;
  border-radius: 12px;
  padding: 60px 30px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

@media (max-width: 768px) {
  .review-header {
    flex-direction: column;
    gap: 20px;
  }
  
  .property-info {
    flex-direction: column;
  }
  
  .property-image {
    width: 100%;
    height: 200px;
  }
  
  .rating-breakdown {
    grid-template-columns: 1fr;
  }
  
  .pending-card {
    flex-direction: column;
    gap: 20px;
  }
  
  .reviews-filters {
    flex-direction: column;
  }
}
</style>


